#include "KmyScript.h"
#include <stdlib.h>
#include "../KmyAlgorithm.h"

KmyScript::KmyScript()
{
//    IP = 0;
//    RP = 0;
//    DP = 0;
}

KmyScript::KmyScript(string &name, KmyStream *head_s, KmyStream *body_s, KmyStream *text_s){
//    IP = 0;
//    RP = 0;
//    DP = 0;
    this->name = name;

    string str = head_s->readString();
    while (!str.empty() && str!="end"){
        string anchor_name = str;
        str = head_s->readString();
        int addr = atoi(str.c_str());
        anchor.insert(pair<string, int>(anchor_name, addr));
    }

    str = body_s->readString();
    while (!str.empty() && str!="end"){
        body.push_back(str);
        str = body_s->readString();
    }

    St_Buff *sb = text_s->readUtf8StringBuff();
    while (sb!= NULL && sb->size>0){
        text.push_back(sb);
        sb = text_s->readUtf8StringBuff();
    }
}

KmyScript::~KmyScript(){

}

void KmyScript::finalize(){
    anchor.clear();
    body.clear();

    for (int i=0; i<text.size(); i++){
        St_Buff *sb = text.at(i);
        delete sb;
    }
    text.clear();

    if (!port_var.empty()) {
        map<string, KmyVar*>::iterator iter = port_var.begin();
        for (; iter!=port_var.end(); iter++){
            delete iter->second;
        }
        port_var.clear();
    }
}

int KmyScript::getAnchorAddr(const string &Anchor){
    map<string, int>::iterator iter = anchor.find(Anchor);
    if (iter!=anchor.end()){
        int addr = iter->second;
        return addr;
    }else{
        return -1;
    }
}

string KmyScript::getInstruction(int ip){
    if (ip>=body.size()){
        return "";
    }
    return body.at(ip);
}

//int KmyScript::run(){
//    if (IP>=body.size()){
//        return SCRIPT_RESULT_FAIL;
//    }
//    string *inst = body.at(IP);
//    IP++;

//    return SCRIPT_RESULT_SUCCESS;
//}

//bool KmyScript::gotoaddr(string &label){
//    map<string, int>::iterator iter = anchor.find(label);
//    if (iter!=anchor.end()){
//        int addr = iter->second;
//        IP = addr;
//        return true;
//    }else{
//        return false;
//    }
//}
